package com.yzt.javacv;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 * @author Yang_ZT
 *
 */
public class App extends JFrame {

	private static final long serialVersionUID = 1L;

	/**
	 * 视频截图帧数
	 */
	public static int GLOBAL_FRAMES = 1;
	/**
	 * 视频压缩比例
	 */
	public static double GLOBAL_SCALE = 0.02;

	/**
	 * 视频截图按钮
	 */
	public static JButton sBtn;
	/**
	 * 视频压缩按钮
	 */
	public static JButton cBtn;

	/**
	 * 文字输出域
	 */
	public static JTextArea jTextArea;

	/**
	 * 文字输出框
	 */
	public static JTextField jTextField;
	/**
	 * 文件选择按钮
	 */
	public static JButton fBtn;

	public static JFileChooser jFileChooser;
	public static JScrollBar jScrollBar;
	public static JScrollPane jScrollPane;

	public static JMenuBar jMenuBar;
	public static JMenu sMenu;
	public static JMenu cMenu;
	public static JMenuItem cTarItem;
	public static JMenuItem sTarItem;

	public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public static ExecutorService executorService = Executors.newFixedThreadPool(3);

	public static boolean isRun = false;
	public static int index = 0;

	public final static String lock = "lock";

	public App() {
		this.setTitle("视频处理");
		this.setSize(800, 620);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setLocationRelativeTo(null);
		this.setResizable(false);
		FlowLayout flowLayout = new FlowLayout();
		this.setLayout(flowLayout);
	}

	public static void main(String[] args) throws Exception {
		App app = new App();
		initMenuBar(app);
		initFileChoose(app);
		initText(app);
		initBtn(app);
		app.setVisible(true);
	}

	public static JMenu initSMenu() {
		sMenu = new JMenu("截图帧数");
		for (int i = 0; i <= 10; i++) {
			int frames = i == 0 ? 1 : i * 15;
			JMenuItem item = new JMenuItem("第" + frames + "帧");
			item.addActionListener(new CActionLisnter(frames));
			sMenu.add(item);
		}
		JMenuItem item = new JMenuItem("其他");
		item.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				String inputValue = JOptionPane.showInputDialog("请输入帧数:");
				Pattern p = Pattern.compile("\\d+");
				Matcher m = p.matcher(inputValue);
				boolean b = m.matches();
				if (b) {

					JMenuItem item = (JMenuItem) e.getSource();

					if (App.sTarItem != null) {
						App.sTarItem.setBackground(item.getBackground());
					}

					item.setBackground(Color.LIGHT_GRAY);

					App.sTarItem = item;

					App.GLOBAL_FRAMES = Integer.valueOf(inputValue);
					App.jTextArea.append(App.sdf.format(new Date()) + "视频截图已定为： 第" + App.GLOBAL_FRAMES + "帧\n");
					App.jScrollBar.setValue(App.jScrollBar.getMaximum());
				} else {
					JOptionPane.showMessageDialog(null, "请输入整数");
				}
			}
		});
		sMenu.add(item);

		return sMenu;
	}

	public static JMenu initCMenu() {
		cMenu = new JMenu("压缩比");
		for (int i = 0; i < 10; i++) {
			double scale = (i + 1) / 100.0;
			JMenuItem item = new JMenuItem("" + scale);
			item.addActionListener(new SActionLisnter(scale));
			if (i == 1) {
				cTarItem = item;
				item.setBackground(Color.LIGHT_GRAY);
			}
			cMenu.add(item);
		}
		return cMenu;
	}

	public static void initMenuBar(App app) {
		jMenuBar = new JMenuBar();
		jMenuBar.add(initSMenu());
		jMenuBar.add(initCMenu());
		app.setJMenuBar(jMenuBar);
	}

	public static void initFileChoose(App app) {
		jFileChooser = new JFileChooser();
		jFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		jFileChooser.setMultiSelectionEnabled(true);

		jTextField = new JTextField(50);
		jTextField.setPreferredSize(new Dimension(700, 30));
		jTextField.setEditable(false);

		fBtn = new JButton("选择文件");

		fBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				int i = jFileChooser.showOpenDialog(app.getContentPane());
				if (i == JFileChooser.APPROVE_OPTION) {
//					File file = jFileChooser.getSelectedFile();
					File[] files = jFileChooser.getSelectedFiles();
					String filePaths = "";
					for (int j = 0; j < files.length; j++) {
						File f = files[j];
						if (j == 0) {
							filePaths += f.getAbsolutePath();
						} else {
							filePaths += "|" + f.getAbsolutePath();
						}
					}
					jTextField.setText(filePaths);
				}
			}
		});

		app.add(jTextField);
		app.add(fBtn);
	}

	public static void initText(App app) {
		jScrollPane = new JScrollPane();

		jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

		jTextArea = new JTextArea(30, 70);
		jTextArea.setEditable(false);
		jTextArea.setText(sdf.format(new Date()) + "--请选择要处理的视频文件..........\n");

		JPopupMenu menu = new JPopupMenu();
		JMenuItem clear = new JMenuItem("清空");
		menu.add(clear);
		app.add(menu);

		jScrollPane.setViewportView(jTextArea);
		jScrollPane.setBounds(0, 0, 800, 550);

		jScrollBar = jScrollPane.getVerticalScrollBar();

		app.add(jScrollPane);

		jTextArea.addMouseListener(new MouseAdapter() {

			@Override
			public void mousePressed(MouseEvent e) {
				int mods = e.getModifiers();
				// 鼠标右键
				if (mods == MouseEvent.BUTTON3_MASK) {
					// 弹出菜单
					menu.show(e.getComponent(), e.getX() + 5, e.getY());
				}
			}

		});
		clear.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				jTextArea.setText("");
			}
		});
	}

	public static void initBtn(App app) {
		sBtn = new JButton("视频截图");
		cBtn = new JButton("视频压缩");
		app.add(sBtn);
		app.add(cBtn);

		sBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (isRun) {
					return;
				}
				String filePaths = jTextField.getText();
				if (filePaths.equals("")) {
					return;
				}
				String[] filePath = filePaths.split("\\|");
				index = -1;
				for (int i = 0; i < filePath.length; i++) {
					isRun = true;
					executorService.execute(() -> VideoScreenshots.screenshots(filePath[++index]));
				}

				new Thread(() -> {
					while (true) {
						ThreadPoolExecutor executor = (ThreadPoolExecutor) executorService;
						if (executor.getActiveCount() == 0) {
							isRun = false;
							System.out.println("................OVER...........");
							break;
						}
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e1) {
							e1.printStackTrace();
						}
						System.out.println(".................RUN.............");
					}
				}).start();
			}
		});

		cBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (isRun) {
					return;
				}
				String filePaths = jTextField.getText();
				if (filePaths.equals("")) {
					return;
				}
				String[] filePath = filePaths.split("\\|");
				index = -1;
				isRun = true;
				for (int i = 0; i < filePath.length; i++) {
					executorService.execute(() -> VideoCompression.compression(filePath[++index]));
				}
				new Thread(() -> {
					while (true) {
						ThreadPoolExecutor executor = (ThreadPoolExecutor) executorService;
						if (executor.getActiveCount() == 0) {
							isRun = false;
							System.out.println("................OVER...........");
							break;
						}
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e1) {
							e1.printStackTrace();
						}
						System.out.println(".................RUN.............");
					}
				}).start();
			}
		});
	}

}

class CActionLisnter implements ActionListener {

	private int frames;

	public CActionLisnter(int frames) {
		this.frames = frames;
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		JMenuItem item = (JMenuItem) e.getSource();

		if (App.sTarItem != null) {
			App.sTarItem.setBackground(item.getBackground());
		}

		item.setBackground(Color.LIGHT_GRAY);

		App.sTarItem = item;

		App.GLOBAL_FRAMES = frames;
		App.jTextArea.append(App.sdf.format(new Date()) + "视频截图已定为： 第" + App.GLOBAL_FRAMES + "帧\n");
		App.jScrollBar.setValue(App.jScrollBar.getMaximum());
	}

}

class SActionLisnter implements ActionListener {

	private double scale;

	public SActionLisnter(double scale) {
		this.scale = scale;
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		JMenuItem item = (JMenuItem) e.getSource();

		if (App.cTarItem != null) {
			App.cTarItem.setBackground(item.getBackground());
		}

		item.setBackground(Color.LIGHT_GRAY);

		App.cTarItem = item;

		App.GLOBAL_SCALE = scale;
		App.jTextArea.append(App.sdf.format(new Date()) + "视频压缩比定为：" + App.GLOBAL_SCALE + "\n");
		App.jScrollBar.setValue(App.jScrollBar.getMaximum());
	}

}
